/**
 * Copyright (C) 2013 Oleg Anastassov <oleg.anastassov@gmail.com>
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package kz.kstu.loc.desktop.dialogs;

import kz.kstu.loc.business.extract.Extractor;
import kz.kstu.loc.business.extract.strategy.ExcelExtractStrategy;
import kz.kstu.loc.business.patch.Patcher;
import kz.kstu.loc.desktop.chooser.CustomFileChooser;
import kz.kstu.loc.desktop.chooser.filter.ExcelFileFilter;
import kz.kstu.loc.desktop.chooser.filter.PropFileFilter;
import kz.kstu.loc.desktop.icon.GUIFactory;
import kz.kstu.loc.desktop.icon.GUIIcon;
import kz.kstu.loc.entity.Item;
import kz.kstu.loc.util.GUIUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.List;


/**
 * Date: 19.01.2013
 * Time: 17:36
 *
 * @author Oleg Anastassov
 */
public class PatchDialog extends ADialog {

    private static final String TITLE = "Патч файла ресурсов...";

    private static final int WIDTH = 500;
    private static final int HEIGHT = 140;

    private JTextField filePathTextField;
    private JButton chooseFileButton;
    private JButton patchButton;

    public PatchDialog() {
        Timer timer = new Timer(100, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                patchButton.setEnabled(!filePathTextField.getText().isEmpty());
            }
        });
        timer.start();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void initDialog() {
        setTitle(TITLE);
        setSize(new Dimension(WIDTH, HEIGHT));
        setIconImage(GUIFactory.getImage(GUIIcon.PATCH));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void initStaticComponents() {
        JPanel grid = new JPanel(new GridLayout(2, 3));
        grid.setBorder(BorderFactory.createTitledBorder("Импорт файла Excel"));
        filePathTextField = new JTextField();
        filePathTextField.setEnabled(false);
        grid.add(filePathTextField);

        JPanel b = new JPanel(new GridLayout());
        chooseFileButton = new JButton("Обзор");
        chooseFileButton.setIcon(GUIFactory.getIcon(GUIIcon.BROWSE));
        patchButton = new JButton("Патч");
        patchButton.setIcon(GUIFactory.getIcon(GUIIcon.PATCH));
        patchButton.setEnabled(false);
        b.add(chooseFileButton);
        b.add(Box.createVerticalGlue());
        b.add(patchButton);
        grid.add(b);
        add(grid);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void initListeners() {
        chooseFileButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fc = new CustomFileChooser(new ExcelFileFilter(), "Выбрать файл для импорта готовых текстовых элементов");
                int result = fc.showOpenDialog(getContentPane());
                if (result == JFileChooser.CANCEL_OPTION || result == JFileChooser.ABORT) {
                    return;
                }
                File selectedFile = fc.getSelectedFile();
                String path = selectedFile.getAbsolutePath();
                filePathTextField.setText(path);
            }
        });
        patchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                final ProgressDialog pd = new ProgressDialog();
                Thread t = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        File f = new File(filePathTextField.getText());
                        if (f.exists()) {
                            Extractor ext = new Extractor(f, new ExcelExtractStrategy());
                            List<Item> items = ext.extract();
                            if (items.isEmpty()) {
                                JOptionPane.showMessageDialog(getContentPane(),
                                        "В файле '" + f.getAbsolutePath() + "'\n" +
                                                "нет текстовых элементов.",
                                        "Предупреждение",
                                        JOptionPane.WARNING_MESSAGE
                                );
                            } else {
                                JFileChooser fc = new CustomFileChooser(new PropFileFilter(), "Выбор файла ресурсов для патча");
                                fc.setApproveButtonText("Патч");
                                int result = fc.showSaveDialog(getContentPane());
                                if (result == JFileChooser.CANCEL_OPTION || result == JFileChooser.ABORT) {
                                    return;
                                }
                                File selectedFile = fc.getSelectedFile();
                                Patcher p = new Patcher();
                                long patchedCount = p.patch(selectedFile, items); // сохраниь оригинальный файл = true
                                if (patchedCount > 0) {
                                    JOptionPane.showMessageDialog(getContentPane(),
                                            "Файл '" + f.getAbsolutePath() + "'\n" +
                                                    "успешно пропатчен.\n" +
                                                    "Заменено текстовых элементов: " + patchedCount,
                                            "Операция",
                                            JOptionPane.INFORMATION_MESSAGE
                                    );
                                } else {
                                    JOptionPane.showMessageDialog(getContentPane(),
                                            "Файл '" + f.getAbsolutePath() + "'\n" +
                                                    "не содежит подходящих строк для патча.\n" +
                                                    "Заменено текстовых элементов: " + patchedCount,
                                            "Предупреждение",
                                            JOptionPane.WARNING_MESSAGE
                                    );
                                }
                            }
                        } else {
                            JOptionPane.showMessageDialog(getContentPane(),
                                    "Файл '" + f.getAbsolutePath() + "' не найден.\n" +
                                            "Возможно он был перемещен или удален.",
                                    "Ошибка",
                                    JOptionPane.ERROR_MESSAGE
                            );
                        }
                        pd.dispose();
                    }
                });
                t.start();
                GUIUtils.centerAndShow(pd);
            }
        });
    }

}
